package com.hzjh.base.ext.utils

import android.content.Context
import android.os.Build
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hzjh.base.ext.R
import com.hzjh.base.log.JHLogger
import com.hzjh.base.style.weight.ToastKt.toastCenter
import com.hzjh.base.utils.other.CheckUtils
import com.hzjh.base.utils.other.CommUtils
import com.hzjh.base.utils.other.FastUtils
import com.hzjh.base.utils.other.FilesUtils
import com.hzjh.base.web.okhttp.CallBackUtil
import com.hzjh.base.web.okhttp.OkhttpUtil
import okhttp3.Call
import okio.ByteString.Companion.encodeUtf8
import java.io.File

object DownloadUtils {
    private fun realDownload(context:Context,
                             pathList: List<String>,
                             callBack:((Boolean)->Unit)?=null){
        if(FastUtils.isFast(5000)){
            context.toastCenter(CommUtils.getString(R.string.jh_download_ing))
            return
        }
        var num = 0
        pathList.forEach {url->
            //文件类型
            var fileTypeStr=url.substring(url.lastIndexOf("."))
            if (CheckUtils.isEmpty(fileTypeStr) || fileTypeStr.contains("?") || fileTypeStr.contains("&")) {
                //兼容无后缀的视频链接
                fileTypeStr = ".jpg"
            }
            val webCachePath = getDownloadCachePath()
            val destFileName=url.encodeUtf8().md5().hex()+fileTypeStr
            val cacheFilePath =
                webCachePath + File.separator + "success-" + destFileName // 自定义文件命名规则
            val cacheFile = File(cacheFilePath)
            OkhttpUtil.okHttpDownloadFile(url,object :
                CallBackUtil.CallBackFile(webCachePath,destFileName) {
                override fun onFailure(call: Call?, e: java.lang.Exception?) {
                    JHLogger.d("FAIL--Download缓存失败 $url")
                    callBack?.invoke(false)
                }

                override fun onResponse(call: Call?, response: File?) {
                    // 下载完成后增加 "success-" 前缀 代表文件无损 【防止io流被异常中断导致文件损坏 无法判断】
                    response?.renameTo(cacheFile)
                    val filePath=FilesUtils.saveToAlbum(
                        context,
                        cacheFile.absolutePath,
                        destFileName
                    )

                    JHLogger.d("SUCCESS--Download缓存成功 $url --- $filePath")
                    num++
                    if(num==pathList.size){
                        callBack?.invoke(true)
                    }
                }
            })
        }
    }
    fun download(context:Context
                         ,pathList: List<String>
                         ,callBack:((Boolean)->Unit)?=null){
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
            reqUpVersionQ(context,pathList,callBack)
        }else{
            reqDownVersionQ(context,pathList,callBack)
        }

    }

    private fun reqUpVersionQ(context:Context
                            , pathList: List<String>
                            , callBack:((Boolean)->Unit)?=null){
        XXPermissions.with(context)
            // 申请单个权限
            .permission(Permission.READ_MEDIA_IMAGES)
            // 申请多个权限
            .permission(Permission.READ_MEDIA_VIDEO)
            // 设置权限请求拦截器（局部设置）
            //.interceptor(new PermissionInterceptor())
            // 设置不触发错误检测机制（局部设置）
            //.unchecked()
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        context.toastCenter(CommUtils.getString(R.string.jh_file_permission))
                        return
                    }
                    realDownload(context, pathList, callBack)
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        JHLogger.d("被永久拒绝授权")
                        context.toastCenter(CommUtils.getString(R.string.jh_file_permission))
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(context, permissions)
                    } else {
                        JHLogger.d("获取权限失败")
                        context.toastCenter(CommUtils.getString(R.string.jh_file_permission))
                    }
                }
            })
    }

    private fun reqDownVersionQ(context:Context
                              , pathList: List<String>
                              , callBack:((Boolean)->Unit)?=null){
        XXPermissions.with(context)
            // 申请单个权限
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            // 设置权限请求拦截器（局部设置）
            //.interceptor(new PermissionInterceptor())
            // 设置不触发错误检测机制（局部设置）
            //.unchecked()
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        context.toastCenter(CommUtils.getString(R.string.jh_file_permission))
                        return
                    }
                    realDownload(context, pathList, callBack)
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        JHLogger.d("被永久拒绝授权")
                        context.toastCenter(CommUtils.getString(R.string.jh_file_permission))
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(context, permissions)
                    } else {
                        JHLogger.d("获取权限失败")
                        context.toastCenter(CommUtils.getString(R.string.jh_file_permission))
                    }
                }
            })
    }

    /**
     * 获取 download 缓存文件目录
     */
    private fun getDownloadCachePath(): String{
        return FilesUtils.getInstance().createSDDir("download").absolutePath
    }
}